package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.entity.request.ClientGrowthReqPara;
import com.lst.entity.response.ClientGrowthResPara;
import com.lst.model.ClientAccomplish;
import com.lst.model.ClientGrowth;
import com.lst.model.MstGrade;
import com.lst.service.ClientGrowthService;
import com.lst.service.MstGradeService;
import com.lst.servlet.BaseServlet;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

public class InviteFriendsServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private ClientGrowthService clientGrowthService = ctx.getBean(ClientGrowthService.class); 

	private ClientAccomplishMapper clientAccomplishMapper = ctx.getBean(ClientAccomplishMapper.class);

	private MstGradeService mstGradeService = ctx.getBean(MstGradeService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		ClientGrowthResPara resPara = new ClientGrowthResPara();

		try {
			ClientGrowthReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer clientid = Integer.valueOf(reqPara.getUserid());
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());		

				Map<String, Object> cgMap = new HashMap<String, Object>();

				cgMap.put("enabled", true);
				cgMap.put("isDeleted", false);
				cgMap.put("clientid", clientid);
				cgMap.put("growthtype", CommCode.SYSTEM_GROWTH_RANGE_REGISTER_INVITE);
				cgMap.put("orderByClause", "cg.createdate desc");

				PageBounds pageBounds = new PageBounds(page , pagesize);

				PageBounds pagebounds = new PageBounds();

				List<ClientGrowth> cgList = clientGrowthService.queryList(cgMap, pageBounds);				

				for(ClientGrowth cg : cgList){
					String mobile = cg.getMc().getMobileno().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
					cg.getMc().setMobile(mobile);

					Map<String, Object> invitemap = new HashMap<String, Object>();

					invitemap.put("enabled", true);
					invitemap.put("isDeleted", false);
					invitemap.put("orderByClause", "mg.gravalue asc");

					List<MstGrade> mglist = mstGradeService.queryByList(invitemap,pagebounds);

					String graname = "菜鸟";// 初始化头衔

					List<ClientAccomplish> caplist = clientAccomplishMapper.queryByUser(cg.getGrowthid());

					Integer grade = caplist.get(0).getGrade();// 等级

					for (MstGrade mg : mglist) {
						if (grade == mg.getGravalue()) {
							graname = mg.getGraname();// 头衔
							break;
						}
					}
					
					cg.getMc().setGrade(grade);
					cg.getMc().setGraname(graname);
				}
				resPara.setCglist(cgList);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}			

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			logger.info("InviteFriendsServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientGrowthReqPara getReqPara(HttpServletRequest request) {

		ClientGrowthReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ClientGrowthReqPara());

			reqPara = (ClientGrowthReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");


			logger.info("reqPara userid: " + userid);
			logger.info("reqPara page: " + page);
			logger.info("reqPara pagesize: " + pagesize);		

			reqPara.setUserid(userid);
			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);					

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}
		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ClientGrowthReqPara cgReqPara = (ClientGrowthReqPara) reqPara;
		ClientGrowthResPara cgResPara = (ClientGrowthResPara) resPara;

		if (StringUtils.isEmpty(cgReqPara.getUserid())) {
			cgResPara.setCode(CommCode.M_A000000);
			cgResPara.setMessage(CommCode.M_P000002);
		} else if(StringUtils.isEmpty(cgReqPara.getPage())){
			cgResPara.setCode(CommCode.M_A000000);
			cgResPara.setMessage(CommCode.M_P000009);
		} else if(StringUtils.isEmpty(cgReqPara.getPagesize())){
			cgResPara.setCode(CommCode.M_A000000);
			cgResPara.setMessage(CommCode.M_P000010);
		} else {
			flag = true;
		}
		return  flag;
	}

}
